<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    :width="640"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import {
    createDataSource,
    updateDataSource,
    type ServiceDataSource,
    type CreateDataSourcePayload,
    type UpdateDataSourcePayload,
  } from '/@/api/service/dataSource';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n();
  const { showMessage } = useMessage();

  const isUpdate = ref(false);
  const recordData = ref<ServiceDataSource | null>(null);
  const deviceId = ref<string>('');

  const getTitle = computed(() => (unref(isUpdate) ? '修改数据源' : t('tb.dataSourceInfo.add')));

  const formSchema: FormSchema[] = [
    {
      field: 'data_source_id',
      label: t('tb.dataSourceInfo.columns.id'),
      component: 'Input',
      required: true,
      componentProps: ({ formModel }) => ({
        disabled: unref(isUpdate),
        placeholder: '请输入数据源ID',
      }),
    },
    {
      field: 'name',
      label: t('tb.dataSourceInfo.columns.name'),
      component: 'Input',
      required: true,
      componentProps: {
        placeholder: '请输入数据源名称',
      },
    },
    {
      field: 'type',
      label: t('tb.dataSourceInfo.columns.type'),
      component: 'Select',
      required: true,
      componentProps: {
        options: [
          { label: '数据库', value: 'database' },
          { label: 'API', value: 'api' },
          { label: '文件', value: 'txt' },
        ],
      },
    },
    {
      field: 'db_type',
      label: '数据库类型',
      component: 'Select',
      required: true,
      ifShow: ({ values }) => values.type === 'database',
      componentProps: {
        options: [
          { label: 'MySQL', value: 'mysql' },
          { label: 'PostgreSQL', value: 'postgresql' },
          { label: 'SQL Server', value: 'sqlserver' },
        ],
      },
    },
    {
      field: 'host',
      label: t('tb.dataSourceInfo.columns.ip'),
      component: 'Input',
      required: true,
      componentProps: {
        placeholder: '请输入IP地址',
      },
    },
    {
      field: 'port',
      label: t('tb.dataSourceInfo.columns.port'),
      component: 'Input',
      required: true,
      componentProps: {
        placeholder: '请输入端口号',
      },
    },
    {
      field: 'user',
      label: t('tb.dataSourceInfo.columns.username'),
      component: 'Input',
      required: true,
      componentProps: {
        placeholder: '请输入用户名',
      },
    },
    {
      field: 'password',
      label: t('tb.dataSourceInfo.columns.password'),
      component: 'InputPassword',
      required: true,
      componentProps: {
        placeholder: '请输入密码',
      },
    },
    {
      field: 'database',
      label: '数据库名称',
      component: 'Input',
      required: true,
      ifShow: ({ values }) => values.type === 'database',
      componentProps: {
        placeholder: '请输入数据库名称',
      },
    },
    {
      field: 'table',
      label: '数据表',
      component: 'Input',
      required: false,
      ifShow: ({ values }) => values.type === 'database',
      componentProps: {
        placeholder: '请输入数据表名称，多个用逗号分隔',
      },
    },
    {
      field: 'owner',
      label: t('tb.dataSourceInfo.columns.owner'),
      component: 'Input',
      required: true,
      componentProps: {
        placeholder: '请输入创建人',
      },
    },
    {
      field: 'remark',
      label: t('tb.dataSourceInfo.columns.remark'),
      component: 'InputTextArea',
      required: false,
      componentProps: {
        placeholder: '请输入说明',
        rows: 3,
      },
    },
  ];

  const [registerForm, { validate, setFieldsValue, resetFields }] = useForm({
    labelWidth: 120,
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { span: 24 },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });

    isUpdate.value = !!data?.isUpdate;
    deviceId.value = data?.deviceId || '';

    if (unref(isUpdate) && data.record) {
      recordData.value = data.record;
      const record = data.record as ServiceDataSource;

      // 处理 table 字段
      let tableValue = '';
      if (record.table) {
        if (Array.isArray(record.table)) {
          tableValue = record.table.join(',');
        } else {
          tableValue = record.table;
        }
      }

      setFieldsValue({
        data_source_id: record.data_source_id,
        name: record.name,
        type: record.type,
        db_type: record.db_type,
        host: record.host,
        port: record.port,
        user: record.user,
        password: record.password,
        database: record.database,
        table: tableValue,
        owner: record.owner,
        remark: record.remark,
      });
    } else if (data?.type) {
      // 新增时设置默认类型
      setFieldsValue({
        type: data.type,
      });
    }
  });

  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });

      // 处理 table 字段
      let tableArray: string[] = [];
      if (values.table && typeof values.table === 'string') {
        tableArray = values.table
          .split(',')
          .map((t) => t.trim())
          .filter((t) => t);
      } else if (Array.isArray(values.table)) {
        tableArray = values.table;
      }

      const payload: any = {
        ...values,
        table: tableArray,
        create_time: new Date().toISOString(),
      };

      if (unref(isUpdate) && recordData.value) {
        // 修改时需要包含只读字段
        const updatePayload: UpdateDataSourcePayload = {
          ...payload,
          '.name': recordData.value['.name'],
          '.index': recordData.value['.index'],
          __index: recordData.value.__index || recordData.value['.index'],
        };
        await updateDataSource(deviceId.value, updatePayload);
        showMessage('修改数据源成功', 'success');
      } else {
        // 新增
        const createPayload: CreateDataSourcePayload = payload;
        await createDataSource(deviceId.value, createPayload);
        showMessage('新增数据源成功', 'success');
      }

      closeModal();
      emit('success');
    } catch (error: any) {
      console.error('提交数据源失败:', error);
      showMessage(error.message || '提交失败', 'error');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  function handleCancel() {
    closeModal();
  }
</script>
